import React, { Component } from 'react'

import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

import moment from 'moment'
import Moment from 'react-moment'
import { withNavigation } from 'react-navigation'
import {
  FlatList,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native'
import { List } from 'antd-mobile'
import { Icon, IconButton } from '../components'

import store from '../store'

const { Item } = List
const { Brief } = Item

const QUERY_ORDERS = gql`
  query($customerId: ID!) {
    allOrders(
      filter: { customer: { id: $customerId } }
      orderBy: updatedAt_DESC
    ) {
      id
      items {
        item {
          id
          title
          price
        }
        amount
      }
      state
      createdAt
      updatedAt
    }
  }
`

@graphql(QUERY_ORDERS, {
  options: () => ({
    variables: { customerId: store.user.id },
  }),
})
export class OrdersScreen extends Component {
  render = () =>
    (({ data }) => (
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <Orders
          data={data['allOrders'] || []}
          loading={data.loading}
          onRefresh={data.refetch}
        />
      </View>
    ))(this.props)
}

export const Orders = withNavigation(
  ({ data, loading, onRefresh, navigation }) => (
    <FlatList
      data={data}
      refreshing={loading}
      onRefresh={onRefresh}
      keyExtractor={x => x.id}
      renderItem={({ item }) => <OrdersItem data={item} />}
    />
  ),
)

const OrdersItem = withNavigation(({ data, navigation }) => (
  <TouchableOpacity
    style={styles.container}
    onPress={() => navigation.navigate('Order', { id: data.id })}
  >
    <View style={styles.content}>
      {data.items.map((t, i) => (
        <Text style={styles.name} key={i}>
          {`${t.item.title} (${t.amount})`}
        </Text>
      ))}
    </View>
    <View style={styles.offside}>
      <Text style={styles.state}>
        {data.state}
        {'  '}
      </Text>
      <Moment calendar>{data.updatedAt}</Moment>
    </View>
  </TouchableOpacity>
))

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: 'whitesmoke',
  },
  content: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'space-around',
    paddingVertical: 5,
  },
  name: {
    marginLeft: 15,
    marginVertical: 5,
  },
  state: {
    color: 'slategray',
  },
  offside: {
    flexDirection: 'row',
    paddingHorizontal: 15,
  },
})
